const express = require('express');
const cors = require('cors');
const pool = require('./db');

const app = express();
// 配置CORS，允许所有来源的请求
app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type']
}));
app.use(express.json());

// 用户登录/注册
app.post('/api/login', async (req, res) => {
    const { username } = req.body;
    try {
        await pool.query(
            'INSERT INTO users (username) VALUES (?) ON DUPLICATE KEY UPDATE username=username',
            [username]
        );
        res.json({ success: true, username });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
});

// 获取用户存档
app.get('/api/saves/:username', async (req, res) => {
    const { username } = req.params;
    console.log('开始获取存档, 用户名:', username);
    try {
        console.log('执行查询: SELECT * FROM game_saves WHERE username = ? ORDER BY saved_at DESC');
        const [saves] = await pool.query(
            'SELECT * FROM game_saves WHERE username = ? ORDER BY saved_at DESC',
            [username]
        );
        console.log('查询结果:', saves);
        res.json({ success: true, saves });
    } catch (error) {
        console.error('获取存档失败, 错误详情:', error);
        res.status(500).json({ success: false, message: error.message });
    }
});

// 隐藏存档
app.put('/api/saves/:id/hide', async (req, res) => {
    const { id } = req.params;
    try {
        await pool.query(
            'UPDATE game_saves SET is_hidden = TRUE WHERE id = ?',
            [id]
        );
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
});

// 保存游戏
app.post('/api/save', async (req, res) => {
    const { username, gameState, currentScore, saveId } = req.body;
    try {
        // 先检查用户是否存在，不存在则创建
        const [users] = await pool.query('SELECT * FROM users WHERE username = ?', [username]);
        if (users.length === 0) {
            await pool.query(
                'INSERT INTO users (username, highest_score) VALUES (?, ?)',
                [username, currentScore]
            );
        }

        if (saveId) {
            // 更新已有存档
            await pool.query(
                'UPDATE game_saves SET game_state = ?, current_score = ? WHERE id = ? AND username = ?',
                [JSON.stringify(gameState), currentScore, saveId, username]
            );
        } else {
            // 创建新存档
            await pool.query(
                'INSERT INTO game_saves (username, game_state, current_score) VALUES (?, ?, ?)',
                [username, JSON.stringify(gameState), currentScore]
            );
        }
        
        // 更新最高分
        await pool.query(
            'UPDATE users SET highest_score = GREATEST(highest_score, ?) WHERE username = ?',
            [currentScore, username]
        );
        
        res.json({ success: true });
    } catch (error) {
        console.error('保存游戏失败:', error);
        res.status(500).json({ success: false, message: error.message });
    }
});

// 获取排行榜
app.get('/api/leaderboard', async (req, res) => {
    try {
        const [users] = await pool.query(
            'SELECT username, highest_score FROM users ORDER BY highest_score DESC'
        );
        res.json({ success: true, users });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
});

const PORT = 2049;
// 监听所有网络接口
app.listen(PORT, '0.0.0.0', () => {
    console.log(`服务器运行在 http://0.0.0.0:${PORT}`);
}); 